<?php
/**
 * Created by PhpStorm.
 * User: clcw908
 * Date: 2016/12/27
 * Time: 9:56
 */
namespace AuctionBack\Logic;

use AuctionCore\CarDealer\AssetCenter;
use AuctionCore\CarResource\Car;
use AuctionCore\CarResource\SelfReceiveCar;
use AuctionCore\Finance\Collection;
use AuctionCore\Issue\OwnerIssue;

class RecheckLogic
{

    /**
     * @var bool
     */
    protected $autoCheckFields = false;

    /**
     * 复检编号
     * @var
     */
    protected $rl_id;

    /**
     * @var Model|\Think\Model
     */
    protected $model;

    /**
     * RecheckLogic constructor.
     * @param $id
     */
    public function __construct($id)
    {
        $this->rl_id = $id;
        $this->model = D('Recheck', 'Model');
    }

    /**
     * 通过拍单号，得到复检信息
     *
     * @param int $orderId 拍单号
     * @return mixed
     */
    public static function getDataByOrderId($orderId)
    {
        return D('Recheck', 'Model')->where(['order_id' => $orderId])->find();
    }

    /**
     * 更新复检信息
     * @param $data
     * @return bool
     */
    public function update($data)
    {
        if(empty($data)) return false;
        return $this->model->where(['rl_id' => $this->rl_id])->save($data);
    }

    /**
     * 获取复检详情
     * @return mixed
     */
    public function detail()
    {
        return $this->model->where(['rl_id'=>$this->rl_id])->find();
    }

    /**
     * 复检完成
     * @param $data
     * @return bool
     */
    public function saveRecheck($data)
    {
        if(intval($data['rl_id']) < 1){
            return false;
        }
        if(intval($data['status']) < 1){
            return false;
        }
        $Order = new OrderLogic($data['order_id']);
        $orderInfo = $Order->detail();
        $Car = new Car($data['car_id']);
        $carInfo = $Car->detail();
        //事务开始
        M()->startTrans();
        $recheckData = [
            'condition_checker' => $data['condition_checker'],
            'procedure_checker' => $data['emp_id'],
            'procedures' => trim($data['procedures']),
            'is_car_condition_conform' => $data['is_car_condition_conform'],
            'remark' => $data['condition_desc'],
            'status' => $data['status'],
            'recheck_time' => $data['recheck_time'],
        ];

        $orderData = [];
        $orderData['return_check_status'] = $data['is_car_condition_conform'] == 1 ? 5 : 6 ;
        if($data['status'] == 1){  //继续跟踪
            $recheckData['next_trace_time'] = $data['next_trace_time'];
            $recheckData['remark'] = $data['trace_reason'];
            $orderData['return_check_status'] = 4;
        }elseif($data['status'] == 2){ //复检完成
            //4S店车源
            if ($carInfo['car_source'] == 1) {
                //自收车辆
                if ($carInfo['is_self_receive'] == 1) {
                    $data = [
                        'car_id' => $data['car_id'],
                        'order_id' => $data['order_id'],
                        'compensate_type' => 1,
                        'self_type' => 1
                    ];

                    $self_receive_car = new SelfReceiveCar();
                    $res = $self_receive_car->add_self_receive_car($data);
                    if(!$res){
                        M()->rollback();
                        trace("finishRecheck: add self receive car failed,order_id {$data['order_id']}","","ERROR",true);
                        return false;
                    }

                    $res = $Car->update(['self_receive_price' => $orderInfo['success_price']]);
                    if(!$res){
                        M()->rollback();
                        trace("finishRecheck: update car self_receive_price failed,order_id {$data['order_id']}","","ERROR",true);
                        return false;
                    }
                    $orderData['status'] = 12;
                    $orderData['fail_type'] = 10;  //自收完成
                    //自收车辆复检完成到自收车辆后解冻保证金
                    AssetCenter::unfreeze($orderInfo['success_dealer_id'],$data['order_id']);
                } else {
                    //添加付款跟踪记录
                    Collection::add(['order_id' => $data['order_id']]);
                }
            }

            //个人车况不符的进争议
            if($carInfo['car_source'] == 2 && $data['is_car_condition_conform'] == 2 ) {
                $ownerIssueData = [
                    'order_id' => $data['order_id'],
                    'owner_id' => $carInfo['owner_id']
                ];
                $oi = new OwnerIssue();
                $res = $oi->add_owner_issue($ownerIssueData);
                if ($res < 1) {
                    M()->rollback();
                    trace("finishRecheck: add owner issue failed,order_id {$data['order_id']}","","ERROR",true);
                    return false;
                }
                $orderData['is_owner_issue'] = 1;
            }

        }
        //更新复检信息
        $res = $this->update($recheckData);
        if(!$res){
            M()->rollback();
            trace("finishRecheck: update recheck failed,order_id {$data['order_id']}","","ERROR",true);
            return false;
        }
        //更新拍单信息
        $res = $Order->update($orderData);
        if (!$res) {
            M()->rollback();
            trace("finishRecheck: update order failed,order_id {$data['order_id']}","","ERROR",true);
            return false;
        }
        M()->commit();
        return true;
    }
    
    /*
     * 通过车源id，得到复检信息
     *
     * @param int $sid 车辆id
     * @return mixed
     */
    public static function getDataBySid($sid)
    {
        return D('Recheck', 'Model')->where(['sid' => $sid])->find();
    }
}
